package com.laosg.spring.small.core02.factory.support;

import com.laosg.spring.small.core02.exception.BeansException;
import com.laosg.spring.small.core02.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * <p>description: jkd  </p>
 *
 * @author kevin
 * @date 8/18/21
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(String beanName, BeanDefinition beanDefinition, Constructor constructor, Object[] args) {
        Class beanClass = beanDefinition.getBeanClass();

        try {

            if (null != constructor) {
                return beanClass.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            } else {

                return beanClass.getDeclaredConstructor().newInstance();

            }
        } catch (InstantiationException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("failed to instantiate [" + beanClass.getName() + "]", e);
        }
    }
}
